<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <!-- <el-form-item label="物候期ID" prop="phenologicalperiodid">
        <el-input
          v-model="queryParams.phenologicalperiodid"
          placeholder="请输入物候期ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      
      <!-- <el-form-item label="作物名称" prop="cropname">
  <el-input
    v-model="queryParams.cropname"
    placeholder="请输入作物名称"
    clearable
    @keyup.enter="handleQuery"
  />
</el-form-item> -->

<!-- <el-form-item label="作物名称" prop="cropname">
  <el-select
    v-model="queryParams.cropname"
    placeholder="请选择作物"
    clearable
    filterable
  >
    <el-option
      v-for="item in cropOptions"
      :key="item.cropid"
      :label="item.cropname"
      :value="item.cropname"
    />
  </el-select>
</el-form-item> -->
<el-form-item label="作物名称" prop="cropid">
  <el-select
    v-model="queryParams.cropid"
    placeholder="请选择作物"
    clearable
    filterable
    @change="handleCropChangeSearch"
  >
    <el-option
      v-for="item in cropOptions"
      :key="item.cropid"
      :label="item.cropname"
      :value="item.cropid"
    />
  </el-select>
</el-form-item>

      <!-- <el-form-item label="物候期名称" prop="phenologicalperiodid">
  <el-select
    v-model="queryParams.phenologicalperiodid"
    placeholder="请选择物候期"
    clearable
    filterable
  >
    <el-option
      v-for="item in periodOptions"
      :key="item.phenologicalperiodid"
      :label="item.phenologicalperiodname"
      :value="item.phenologicalperiodid"
    />
  </el-select>
</el-form-item> -->
<!-- <el-form-item label="物候期名称" prop="phenologicalperiodid">
  <el-select v-model="queryParams.phenologicalperiodid" placeholder="请选择物候期" clearable filterable>
    <el-option
      v-for="item in periodOptionsAll"
      :key="item.phenologicalperiodid"
      :label="item.phenologicalperiodname"
      :value="item.phenologicalperiodid"
    />
  </el-select>
</el-form-item> -->
<el-form-item label="物候期名称" prop="phenologicalperiodid">
  <el-select
    v-model="queryParams.phenologicalperiodid"
    placeholder="请选择物候期"
    clearable
    filterable
  >
    <el-option
      v-for="item in periodOptionsSearch"
      :key="item.phenologicalperiodid"
      :label="item.phenologicalperiodname"
      :value="item.phenologicalperiodid"
    />
  </el-select>
</el-form-item>

      <el-form-item label="指导名称" prop="guidancename">
        <el-input
          v-model="queryParams.guidancename"
          placeholder="请输入指导名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="指导类型" prop="guidetype">
  <el-select v-model="queryParams.guidetype" placeholder="请选择指导类型" clearable>
    <el-option
      v-for="item in guidetypeOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</el-form-item> -->
<el-form-item label="指导类型" prop="guidetype" style="width: 240px">
  <el-select
    v-model="queryParams.guidetype"
    placeholder="请选择指导类型"
    clearable
    filterable
    style="width: 100%"
  >
    <el-option
      v-for="item in guidetypeOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</el-form-item>
      <el-form-item label="指导周期" prop="guidanceperiod">
        <el-input
          v-model="queryParams.guidanceperiod"
          placeholder="请输入指导周期"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:phenologicalguidance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:phenologicalguidance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:phenologicalguidance:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"              
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:phenologicalguidance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="phenologicalguidanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="指导ID" align="center" prop="guidanceid" /> -->
      <el-table-column label="作物名称" align="center" prop="cropname" />
      <el-table-column label="物候期名称" prop="phenologicalperiodname" />
      <el-table-column label="指导名称" align="center" prop="guidancename" />
      <el-table-column label="指导类型" prop="guidetype" />
      <el-table-column label="指导周期" align="center" prop="guidanceperiod" />
      <el-table-column label="标准化实施方法" align="center" prop="standardizedImplementation" />
      <el-table-column label="指导相关图像路径" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:phenologicalguidance:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:phenologicalguidance:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标准化生产指导信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="phenologicalguidanceRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="物候期ID" prop="phenologicalperiodid">
          <el-input v-model="form.phenologicalperiodid" placeholder="请输入物候期ID" />
        </el-form-item> -->
        <!-- <el-form-item label="物候期" prop="phenologicalperiodid">
  <el-select
    v-model="form.phenologicalperiodid"
    placeholder="请选择物候期"
    filterable
  >
    <el-option
      v-for="item in periodOptions"
      :key="item.phenologicalperiodid"
      :label="item.phenologicalperiodname"
      :value="item.phenologicalperiodid"
    />
  </el-select>
</el-form-item> -->
        <!-- <el-form-item label="物候期ID" prop="phenologicalperiodid">
  <el-input
    v-model="form.phenologicalperiodid"
    placeholder="请输入物候期ID"
    :disabled="isEdit"
  />
</el-form-item> -->
      <!-- 作物选择 -->
<!-- <el-form-item label="作物名称" prop="cropid">
  <el-select
    v-model="form.cropid"
    placeholder="请选择作物"
    filterable
    :disabled="isEdit"  
    @change="handleCropChange"
  >
    <el-option
      v-for="item in cropOptions"
      :key="item.cropid"
      :label="item.cropname"
      :value="item.cropid"
    />
  </el-select>
</el-form-item> -->
<el-form-item label="作物名称" prop="cropid">
  <el-select
    v-model="form.cropid"
    placeholder="请选择作物"
    filterable
    @change="handleCropChange"
  >
    <el-option v-for="item in cropOptions" :key="item.cropid" :label="item.cropname" :value="item.cropid" />
  </el-select>
</el-form-item>



<!-- 物候期选择 -->
<!-- <el-form-item label="物候期" prop="phenologicalperiodid">
  <el-select
    v-model="form.phenologicalperiodid"
    placeholder="请选择物候期"
    filterable
  >
    <el-option
      v-for="item in periodOptions"
      :key="item.phenologicalperiodid"
      :label="item.phenologicalperiodname"
      :value="item.phenologicalperiodid"
    />
  </el-select>
</el-form-item> -->
    <!-- 对话框：物候期（随作物联动） -->
<el-form-item label="物候期" prop="phenologicalperiodid">
  <el-select v-model="form.phenologicalperiodid" placeholder="请选择物候期" filterable>
    <el-option
      v-for="item in periodOptionsForm"
      :key="item.phenologicalperiodid"
      :label="item.phenologicalperiodname"
      :value="item.phenologicalperiodid"
    />
  </el-select>
</el-form-item>



        <el-form-item label="指导名称" prop="guidancename">
          <el-input v-model="form.guidancename" placeholder="请输入指导名称" />
        </el-form-item>
        <el-form-item label="指导类型" prop="guidetype">
  <el-select
    v-model="form.guidetype"
    placeholder="请选择指导类型"
    clearable
  >
    <el-option
      v-for="item in guidetypeOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</el-form-item>

        <el-form-item label="指导周期" prop="guidanceperiod">
          <el-input v-model="form.guidanceperiod" placeholder="请输入指导周期" />
        </el-form-item>
        <el-form-item label="标准化实施方法" prop="standardizedImplementation">
          <el-input v-model="form.standardizedImplementation" type="textarea" placeholder="请输入内容"  :rows="10"/>
        </el-form-item>
        <el-form-item label="指导相关图像路径" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Phenologicalguidance">
import { listPhenologicalguidance, getPhenologicalguidance, delPhenologicalguidance, addPhenologicalguidance, updatePhenologicalguidance } from "@/api/agriculture/xctl/phenologicalguidance"
import { listGuidanceView } from "@/api/agriculture/xctl/guidanceview"
import { listPhenologicalperiods } from "@/api/agriculture/xctl/phenologicalperiods" // 🔧 添加
import { listCrops } from "@/api/agriculture/xctl/crops" // 路径按你实际项目调整
const isEdit = ref(false)

const cropOptions = ref([])

function loadCropOptions() {
  listCrops({}).then(res => {
    cropOptions.value = res.rows || []
  })
}

const guidetypeOptions = [
  { label: '农事活动', value: '农事活动' },
  { label: '病虫防控', value: '病虫防控' },
  { label: '预警设置', value: '预警设置' },
  { label: '巡园事项', value: '巡园事项' }
]

// const periodOptions = ref([]) // 🔧 下拉数据

// 🔧 获取物候期下拉列表
// function loadPeriodOptions() {
//   listPhenologicalperiods({}).then(res => {
//     periodOptions.value = res.rows || []
//   })
// }

// 原来的：const periodOptions = ref([])
const periodOptionsAll = ref([])     // 用于“搜索表单”的物候期（可全量）
const periodOptionsForm = ref([])    // 用于“新增/编辑对话框”的物候期（随作物联动）

function loadAllPeriods() {
  listPhenologicalperiods({}).then(res => {
    periodOptionsAll.value = res.rows || []
  })
}


const { proxy } = getCurrentInstance()

const phenologicalguidanceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const periodOptionsSearch = ref([])  // 搜索区用的物候期列表

function handleCropChangeSearch(cropid) {
  if (!cropid) {
    periodOptionsSearch.value = []
    queryParams.value.phenologicalperiodid = null
    return
  }
  listPhenologicalperiods({ cropid }).then(res => {
    const rows = res.rows || []
    // 兜底：如果后端没过滤，这里手动过滤一次
    const hasCropField = rows.length && Object.prototype.hasOwnProperty.call(rows[0], 'cropid')
    const filtered = hasCropField ? rows.filter(p => String(p.cropid) === String(cropid)) : rows
    periodOptionsSearch.value = filtered
    queryParams.value.phenologicalperiodid = null
  })
}


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    phenologicalperiodid: null,
    guidancename: null,
    guidanceperiod: null,
    standardizedImplementation: null,
    imageUrl: null,
    guidetype: null,  // ✅ 添加
    cropname: null // ✅ 新增
  },
  rules: {
     cropid: [
    { required: true, message: "作物不能为空", trigger: "change" }
  ],
    phenologicalperiodid: [
      { required: true, message: "物候期不能为空", trigger: "change" }
    ],
    guidancename: [
      { required: true, message: "指导名称不能为空", trigger: "blur" }
    ],
     guidetype: [{ required: true, message: '请选择指导类型', trigger: 'change' }],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询标准化生产指导信息列表 */
// function getList() {
//   loading.value = true
//   listPhenologicalguidance(queryParams.value).then(response => {
//     phenologicalguidanceList.value = response.rows
//     total.value = response.total
//     loading.value = false
//   })
// }
function getList() {
  loading.value = true;
  listGuidanceView(queryParams.value).then(response => {
    phenologicalguidanceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    guidanceid: null,
    phenologicalperiodid: null,
    guidancename: null,
    guidanceperiod: null,
    standardizedImplementation: null,
    imageUrl: null,
    guidetype: null,  // ✅ 添加
    cropid: null // ✅ 新增

  }
  proxy.resetForm("phenologicalguidanceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.guidanceid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
   isEdit.value = false  // 新增时可编辑
  open.value = true
  title.value = "添加标准化生产指导信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _guidanceid = row.guidanceid || ids.value
  getPhenologicalguidance(_guidanceid).then(response => {
    form.value = response.data
    isEdit.value = true   // 编辑时禁用输入框
    open.value = true
    title.value = "修改标准化生产指导信息"
    // 加载该作物的物候期列表
    // handleCropChange(form.value.cropid)
    handleCropChange(form.value.cropid, true)
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["phenologicalguidanceRef"].validate(valid => {
    if (valid) {
      if (form.value.guidanceid != null) {
        updatePhenologicalguidance(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPhenologicalguidance(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _guidanceids = row.guidanceid || ids.value
  proxy.$modal.confirm('是否确认删除标准化生产指导信息编号为"' + _guidanceids + '"的数据项？').then(function() {
    return delPhenologicalguidance(_guidanceids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/phenologicalguidance/export', {
    ...queryParams.value
  }, `phenologicalguidance_${new Date().getTime()}.xlsx`)
}

// // 作物切换时加载该作物的物候期
// function handleCropChange(cropid) {
//   listPhenologicalperiods({ cropid }).then(res => {
//     periodOptions.value = res.rows || []
//     form.value.phenologicalperiodid = null  // 清空之前选择的物候期
//   })
// }
// function handleCropChange(cropid) {
//   if (!cropid) {
//     periodOptions.value = []
//     form.value.phenologicalperiodid = null
//     return
//   }
//   listPhenologicalperiods({ cropid }).then(res => {
//     periodOptions.value = res.rows || []
//     form.value.phenologicalperiodid = null // 清空之前选的物候期
//   })
// }
function handleCropChange(cropid, keepCurrent = false) {
  if (!cropid) {
    periodOptionsForm.value = []
    if (!keepCurrent) form.value.phenologicalperiodid = null
    return
  }
  listPhenologicalperiods({ cropid }).then(res => {
    const rows = res.rows || []
    // 兜底：如果后端没有按 cropid 过滤，这里前端再过滤一遍
    const hasCropField = rows.length && Object.prototype.hasOwnProperty.call(rows[0], 'cropid')
    const filtered = hasCropField ? rows.filter(p => String(p.cropid) === String(cropid)) : rows
    periodOptionsForm.value = filtered
    if (!keepCurrent) form.value.phenologicalperiodid = null
  })
}


getList()
loadAllPeriods()   // ✅ 用新的函数
loadCropOptions()
</script>
